package com.holyn.guofang.view.distinguish;

import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.apkfuns.logutils.LogUtils;
import com.holyn.guofang.R;
import com.holyn.guofang.model.webhttp.wo.ImageBasicWo;
import com.holyn.guofang.presenter.BaseView;
import com.holyn.guofang.presenter.distinguish.ImageElementContract;
import com.holyn.guofang.presenter.distinguish.ImageElementPresenter;
import com.holyn.guofang.view.BaseActivity;
import com.holyn.guofang.viewcommon.itemdecoration.LinearLayoutItemDecoration;
import com.holyn.guofang.viewcommon.multileveltreelist.Node;
import com.vondear.rxtools.RxKeyboardUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Holyn on 2017/7/23.
 */

public class ImageElementActivity extends BaseActivity implements BaseView, ImageElementContract.View{
    private static final int REQUEST_ACTION_POST_IMAGE_ELEMENT = 0x0001;
    private static final int REQUEST_ACTION_POST_IMAGE_ELEMENT_TWO = 0x0002;
    private static final int REQUEST_ACTION_POST_IMAGE_ELEMENT_THREE = 0x0003;

    public static final String INTENT_KEY_IMAGE_CODES = "INTENT_KEY_IMAGE_CODES";

    @BindView(R.id.et_search_key)
    EditText etSearchKey;
    @BindView(R.id.btn_search)
    Button btnSearch;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.btn_submit)
    Button btnSubmit;

    private ImageElementContract.Presenter presenter;
    private List<ImageBasicWo.DataBean> levelOneList = new ArrayList<>();
    private Map<String, List<ImageBasicWo.DataBean>> levelTwoMap = new HashMap<>();
    private int levelTwoRequestIndex = 0;
    private Map<String, List<ImageBasicWo.DataBean>> levelThreeMap = new HashMap<>();
    private int levelThreeAllSize = 0;
    private int levelThreeRequestIndex = 0;

    private ImageElementRecyclerAdapter recyclerAdapter = null;
    private List<Node> nodeList = new ArrayList<>();

    private ImageElementSearchRecyclerAdapter searchRecyclerAdapter;
    private View heardSearchRecyclerView = null;
    private List<Node> searchNodeList = new ArrayList<>();
    private boolean isShowSearchRecyclerView = false;//当前的RecyclerView展示的是否是点击查找展示出来数据


    public static void startForResult(Activity activity, int requestCode){
        Intent intent = new Intent(activity, ImageElementActivity.class);
        activity.startActivityForResult(intent, requestCode);
    }

    public static void startForResult(Fragment fragment, int requestCode){
        Intent intent = new Intent(fragment.getActivity(), ImageElementActivity.class);
        fragment.startActivityForResult(intent, requestCode);
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_image_element;
    }

    @Override
    protected void onMyCreate() {
        ButterKnife.bind(this);
        showToolbar("图形要素");
        initData();
        initView();
    }

    private void initData(){
        presenter = new ImageElementPresenter(this);
        presenter.addView(this);

        presenter.postImageBasicList(REQUEST_ACTION_POST_IMAGE_ELEMENT, "", -1, -1);
    }

    private void initView(){
        rvList.setLayoutManager(new LinearLayoutManager(ImageElementActivity.this));
        rvList.addItemDecoration(new LinearLayoutItemDecoration(ImageElementActivity.this));
    }

    @OnClick({R.id.btn_search, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_search:
                RxKeyboardUtils.hideSoftInput(ImageElementActivity.this);
                searchNodeList.clear();
                String key = etSearchKey.getText().toString().trim();
                if (TextUtils.isEmpty(key)){
                    if (isShowSearchRecyclerView){
                        rvList.setAdapter(recyclerAdapter);
                        recyclerAdapter.notifyDataSetChanged();
                        isShowSearchRecyclerView = false;
                    }
                } else {
                    initSearchResultView(key);
                    isShowSearchRecyclerView = true;
                }

                break;
            case R.id.btn_submit:
                String result;
                if (isShowSearchRecyclerView){
                    result = searchRecyclerAdapter.getSelectImageCodes();
                } else {
                    result = recyclerAdapter.getSelectImageCodes();
                }
                if (result.equals("error")){
                    toastMsg("最多可以选择5个");
                } else {
                    Intent intent = getIntent();
                    intent.putExtra(INTENT_KEY_IMAGE_CODES, result);
                    setResult(Activity.RESULT_OK, intent);
                    ImageElementActivity.this.finish();
                }
                break;
        }
    }

    private void initSearchResultView(String key){
        List<Node> allNodeList = recyclerAdapter.getAllNodes();
        for (Node node: allNodeList){
            if (node.getName().contains(key)){
                node.setChecked(false);
                searchNodeList.add(node);
            }
        }
        searchRecyclerAdapter = new ImageElementSearchRecyclerAdapter(searchNodeList);
        if (heardSearchRecyclerView == null){
            heardSearchRecyclerView = LayoutInflater.from(ImageElementActivity.this).inflate(R.layout.heard_image_element_search, null);
            searchRecyclerAdapter.addHeaderView(heardSearchRecyclerView);
        }
        rvList.setAdapter(searchRecyclerAdapter);

    }

    @Override
    public void requestStart(Integer requestAction) {
        showLoadingDialog();
    }

    @Override
    public void requestError(Integer requestAction, Throwable e) {
        LogUtils.d("requestError...."+e);
        closeLoadingDialog();
    }

    @Override
    public void requestComplete(Integer requestAction) {

    }

    @Override
    public void responseSuccess(int requestAction, ImageBasicWo imageBasicWo) {
        if (requestAction == REQUEST_ACTION_POST_IMAGE_ELEMENT){
            LogUtils.d(imageBasicWo);

            levelOneList = imageBasicWo.getData();
            for (ImageBasicWo.DataBean data : levelOneList){
                presenter.postImageBasicList(REQUEST_ACTION_POST_IMAGE_ELEMENT_TWO, data.getImageCode(), -1, -1);
            }
        } else if (requestAction == REQUEST_ACTION_POST_IMAGE_ELEMENT_TWO){
            if (imageBasicWo.getData() != null){
                if (imageBasicWo.getData().size() > 0){
                    levelTwoMap.put(imageBasicWo.getData().get(0).getParentCode(), imageBasicWo.getData());
                }
            }
            levelTwoRequestIndex ++ ;
            if (levelTwoRequestIndex == levelOneList.size()){
                for (List<ImageBasicWo.DataBean> dataList : levelTwoMap.values()){
                    for (ImageBasicWo.DataBean data : dataList){
                        presenter.postImageBasicList(REQUEST_ACTION_POST_IMAGE_ELEMENT_THREE, data.getImageCode(), -1, -1);
                    }
                }
            }
        } else if (requestAction == REQUEST_ACTION_POST_IMAGE_ELEMENT_THREE){
            if (imageBasicWo.getData() != null){
                if (imageBasicWo.getData().size() > 0){
                    levelThreeMap.put(imageBasicWo.getData().get(0).getParentCode(), imageBasicWo.getData());
                }
            }
            levelThreeRequestIndex ++;

            if (levelThreeAllSize == 0){
                for (List<ImageBasicWo.DataBean> dataList : levelTwoMap.values()){
                    levelThreeAllSize = levelThreeAllSize + dataList.size();
                }
            }
            if (levelThreeRequestIndex == levelThreeAllSize){
                nodeList.clear();
                for (ImageBasicWo.DataBean levelOndeData : levelOneList){
                    Node node1 = new Node(levelOndeData.getImageCode(), "", levelOndeData.getImageCode()+" "+levelOndeData.getImageName());
                    node1.iconExpand = R.drawable.ic_expand_down;
                    node1.iconNoExpand = R.drawable.ic_expand_up;
                    nodeList.add(node1);
                    List<ImageBasicWo.DataBean> levelTwoDataList = levelTwoMap.get(levelOndeData.getImageCode());
                    if (levelTwoDataList != null){
                        if (levelTwoDataList.size() > 0){
                            for (ImageBasicWo.DataBean levelTwoData : levelTwoDataList){
                                Node node2 = new Node(levelTwoData.getImageCode(), levelTwoData.getParentCode(), levelTwoData.getImageCode()+" "+levelTwoData.getImageName());
                                node2.iconExpand = R.drawable.ic_expand_down;
                                node2.iconNoExpand = R.drawable.ic_expand_up;
                                node2.setParent(node1);
                                node1.getChildren().add(node2);
                                List<ImageBasicWo.DataBean> levelThreeDataList = levelThreeMap.get(levelTwoData.getImageCode());
                                if (levelThreeDataList != null){
                                    if (levelThreeDataList.size() > 0){
                                        for (ImageBasicWo.DataBean levelThreeData : levelThreeDataList){
                                            Node node3 = new Node(levelThreeData.getImageCode(), levelThreeData.getParentCode(), levelThreeData.getImageCode()+" "+levelThreeData.getImageName());
                                            node3.setParent(node2);
                                            node2.getChildren().add(node3);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                recyclerAdapter = new ImageElementRecyclerAdapter(rvList, ImageElementActivity.this, nodeList);
                rvList.setAdapter(recyclerAdapter);

                levelOneList.clear();
                levelTwoMap.clear();
                levelThreeMap.clear();

                closeLoadingDialog();

            }
        }
    }
}
